package com.greenantmall.img.utils;

import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.util.LruCache;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;

public class ImageLoader
{
	/**
	 * 闁搞儱澧芥晶鏍磽閹惧磭鎽犻柣銊ュ閻楀疇绠涢崘顏囶潶
	 */
	private LruCache<String, Bitmap> mLruCache;
	/**
	 * 缂佹崘娉曢埢鐓幮ч敓锟�
	 */
	private ExecutorService mThreadPool;
	/**
	 * 缂佹崘娉曢埢鐓幮ч悩鍨暠缂佹崘娉曢埢濂稿极娴兼潙娅ら柨娑樼焸缁垳鎷嬮妶鍕1
	 */
	//private int mThreadCount = 1;
	/**
	 * 闂傚啰鍠庨崹顏堟儍閸曨喚娈堕幖杈鹃檮閺岀喎顕ｉ敓锟�
	 */
	private Type mType = Type.LIFO;
	/**
	 * 濞寸姾顕ф慨鐔兼⒓閻斿嘲鐏�
	 */
	private LinkedList<Runnable> mTasks;
	/**
	 * 閺夌儐鍠涢妤呮儍閸曨厼娈犵紒瀣舵嫹
	 */
	private Thread mPoolThread;
	private Handler mPoolThreadHander;

	/**
	 * 閺夆晜鍔橀、鎴﹀捶閳烘厲缂佹崘娉曢埢濂告儍閸掔寴ndler闁挎稑鐬奸弫銈嗙鎼达絿鑸禝mageView閻犱礁澧介悿鍡涘炊閸撗冾暬
	 */
	private Handler mHandler;

	/**
	 * 鐎殿喗娲栭崣鍡樼▔閿熻姤绋夐鍕舵嫹闂傜绀�1闁汇劌瀚穱濠囧矗閻戣棄娅ら柨娑樼焸濡茶顫㈤。鎻歰olThreadHander闁哄牜浜滈崹鍨叏鐎ｎ亜顕ч悗鐟版湰閸拷
	 */
	private volatile Semaphore mSemaphore = new Semaphore(0);

	/**
	 * 鐎殿喗娲栭崣鍡樼▔閿熻姤绋夐鍕舵嫹闂傜绀�1闁汇劌瀚穱濠囧矗閻戣棄娅ら柨娑樼灱閺佽鲸绂嶆惔锝呮疇缂佸顑嗛惈婊堝礃閸涙潙鍔ュ☉鏃傚枑濠�浣圭▔閿熻姤绋夐鍫熲枎濠靛鍋熼崵搴ｇ矙鐎ｅ墎绀夐梻鍐ㄥ级椤掓盯宕濋悩鎻掑汲濞寸姾顕ф慨鐔兼儍閸曨垽鎷烽悢宄邦唺閺夆晛娲ら幓鈺呮晬鐏炵厧鈻廘IFO闁轰礁鐗婇悘澶嬬▔瀹ュ棙顫栭柡鍕舵嫹
	 */
	private volatile Semaphore mPoolSemaphore;

	private static ImageLoader mInstance;
	


	/**
	 * 闂傚啰鍠庨崹顏堟儍閸曨喚娈堕幖杈鹃檮閺岀喎顕ｉ敓锟�
	 * 
	 * @author zhy
	 * 
	 */
	public enum Type
	{
		FIFO, LIFO
	}


	/**
	 * 闁告娲戠欢銉╂嚔瀹勬壆绻侀悹鍥ュ劚閻ゅ嫭绗熺�ｎ亶鍤犻悹鐑囨嫹
	 * 
	 * @return
	 */
	public static ImageLoader getInstance()
	{

		if (mInstance == null)
		{
			synchronized (ImageLoader.class)
			{
				if (mInstance == null)
				{
					mInstance = new ImageLoader(1, Type.LIFO);
				}
			}
		}
		return mInstance;
	}

	private ImageLoader(int threadCount, Type type)
	{
		init(threadCount, type);
	}

	private void init(int threadCount, Type type)
	{
		// loop thread
		mPoolThread = new Thread()
		{
			@Override
			public void run()
			{
				Looper.prepare();

				mPoolThreadHander = new Handler()
				{
					@Override
					public void handleMessage(Message msg)
					{
						mThreadPool.execute(getTask());
						try
						{
							mPoolSemaphore.acquire();
						} catch (InterruptedException e)
						{
						}
					}
				};
				// 闂佹彃锕ラ弬浣圭▔閿熻姤绋夐鍐х箚闁告瑧鍏橀崳锟�
				mSemaphore.release();
				Looper.loop();
			}
		};
		mPoolThread.start();

		// 闁兼儳鍢茶ぐ鍥ㄦ償閺冨倹鏆忕紒瀣儏缁參寮甸敓鑺ュ緞瑜嶈ぐ鏌ユ偨閵娿儱鏁堕悗娑虫嫹
		int maxMemory = (int) Runtime.getRuntime().maxMemory();
		int cacheSize = maxMemory / 8;
		mLruCache = new LruCache<String, Bitmap>(cacheSize)
		{
			@Override
			protected int sizeOf(String key, Bitmap value)
			{
				return value.getRowBytes() * value.getHeight();
			};
		};

		mThreadPool = Executors.newFixedThreadPool(threadCount);
		mPoolSemaphore = new Semaphore(threadCount);
		mTasks = new LinkedList<Runnable>();
		mType = type == null ? Type.LIFO : type;

	}

	/**
	 * 闁告梻濮惧ù鍥炊閸撗冾暬
	 * 
	 * @param path
	 * @param imageView
	 */
	public void loadImage(final String path, final ImageView imageView)
	{
		// set tag
		imageView.setTag(path);
		// UI缂佹崘娉曢埢锟�
		if (mHandler == null)
		{
			mHandler = new Handler()
			{
				@Override
				public void handleMessage(Message msg)
				{
					ImgBeanHolder holder = (ImgBeanHolder) msg.obj;
					ImageView imageView = holder.imageView;
					Bitmap bm = holder.bitmap;
					String path = holder.path;
					if (imageView.getTag().toString().equals(path))
					{
						imageView.setImageBitmap(bm);
					}
				}
			};
		}

		Bitmap bm = getBitmapFromLruCache(path);
		if (bm != null)
		{
			ImgBeanHolder holder = new ImgBeanHolder();
			holder.bitmap = bm;
			holder.imageView = imageView;
			holder.path = path;
			Message message = Message.obtain();
			message.obj = holder;
			mHandler.sendMessage(message);
		} else
		{
			addTask(new Runnable()
			{
				@Override
				public void run()
				{

					ImageSize imageSize = getImageViewWidth(imageView);

					int reqWidth = imageSize.width;
					int reqHeight = imageSize.height;

					Bitmap bm = decodeSampledBitmapFromResource(path, reqWidth,
							reqHeight);
					addBitmapToLruCache(path, bm);
					ImgBeanHolder holder = new ImgBeanHolder();
					holder.bitmap = getBitmapFromLruCache(path);
					holder.imageView = imageView;
					holder.path = path;
					Message message = Message.obtain();
					message.obj = holder;
					// Log.e("TAG", "mHandler.sendMessage(message);");
					mHandler.sendMessage(message);
					mPoolSemaphore.release();
				}
			});
		}

	}
	
	/**
	 * 婵烇綀顕ф慨鐐寸▔閿熻姤绋夐鍐╁床闁告棑鎷�
	 * 
	 * @param runnable
	 */
	private synchronized void addTask(Runnable runnable)
	{
		try
		{
			// 閻犲洭鏀遍惇鐗堢┍閳ュ啿濞囬梺鎻掗獜缁辨繈姊奸崣澶樺壘mPoolThreadHander濞戞挾鐨爑ll
			if (mPoolThreadHander == null)
				mSemaphore.acquire();
		} catch (InterruptedException e)
		{
		}
		mTasks.add(runnable);
		
		mPoolThreadHander.sendEmptyMessage(0x110);
	}

	/**
	 * 闁告瑦鐗曢崵顓熺▔閿熻姤绋夐鍐╁床闁告棑鎷�
	 * 
	 * @return
	 */
	private synchronized Runnable getTask()
	{
		if (mType == Type.FIFO)
		{
			return mTasks.removeFirst();
		} else if (mType == Type.LIFO)
		{
			return mTasks.removeLast();
		}
		return null;
	}
	
	/**
	 * 闁告娲戠欢銉╂嚔瀹勬壆绻侀悹鍥ュ劚閻ゅ嫭绗熺�ｎ亶鍤犻悹鐑囨嫹
	 * 
	 * @return
	 */
	public static ImageLoader getInstance(int threadCount, Type type)
	{

		if (mInstance == null)
		{
			synchronized (ImageLoader.class)
			{
				if (mInstance == null)
				{
					mInstance = new ImageLoader(threadCount, type);
				}
			}
		}
		return mInstance;
	}


	/**
	 * 闁哄秷顫夊畵涓ageView闁兼儳鍢茬欢閬嶆焻閸屾氨绉奸柣銊ュ鐢洨绱撻埡鍐╃暠閻庣妫勯幏鐗堫殗閿燂拷
	 * 
	 * @param imageView
	 * @return
	 */
	private ImageSize getImageViewWidth(ImageView imageView)
	{
		ImageSize imageSize = new ImageSize();
		final DisplayMetrics displayMetrics = imageView.getContext()
				.getResources().getDisplayMetrics();
		final LayoutParams params = imageView.getLayoutParams();

		int width = params.width == LayoutParams.WRAP_CONTENT ? 0 : imageView
				.getWidth(); // Get actual image width
		if (width <= 0)
			width = params.width; // Get layout width parameter
		if (width <= 0)
			width = getImageViewFieldValue(imageView, "mMaxWidth"); // Check
																	// maxWidth
																	// parameter
		if (width <= 0)
			width = displayMetrics.widthPixels;
		int height = params.height == LayoutParams.WRAP_CONTENT ? 0 : imageView
				.getHeight(); // Get actual image height
		if (height <= 0)
			height = params.height; // Get layout height parameter
		if (height <= 0)
			height = getImageViewFieldValue(imageView, "mMaxHeight"); // Check
																		// maxHeight
																		// parameter
		if (height <= 0)
			height = displayMetrics.heightPixels;
		imageSize.width = width;
		imageSize.height = height;
		return imageSize;

	}

	/**
	 * 濞寸姴钁uCache濞戞搩鍙�楠炲繘宕ｉ弽锔绢伇鐎殿喚濮村ù姗�鎮ч崶椋庣濠碘�冲�归悘澶嬬▔瀹ュ懐鎽犻柛锔哄妼濮樸劍娼婚弬鎸庣null闁靛棴鎷�
	 */
	private Bitmap getBitmapFromLruCache(String key)
	{
		return mLruCache.get(key);
	}

	/**
	 * 鐎靛府鎷稬ruCache濞戞搩鍘介崸濠囧礉閻樿京顏辩�殿喚濮村ù姗�鎮ч敓锟�
	 * 
	 * @param key
	 * @param bitmap
	 */
	private void addBitmapToLruCache(String key, Bitmap bitmap)
	{
		if (getBitmapFromLruCache(key) == null)
		{
			if (bitmap != null)
				mLruCache.put(key, bitmap);
		}
	}

	/**
	 * 閻犱緤绱曢悾绫璶SampleSize闁挎稑鐬奸弫銈嗙鎼粹�崇缂傚倵鏅涘ù姗�鎮ч敓锟�
	 * 
	 * @param options
	 * @param reqWidth
	 * @param reqHeight
	 * @return
	 */
	private int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight)
	{
		// 婵犙勫姇濞存﹢鎮ч崶鈺傜暠閻庣妫勭�癸拷
		int width = options.outWidth;
		int height = options.outHeight;
		int inSampleSize = 1;

		if (width > reqWidth && height > reqHeight)
		{
			// 閻犱緤绱曢悾濠氬礄閸濆嫮鏉介梻鍕噹椤旀梹鎯旈敃锟介幏浼存儎椤旂晫鍨奸悗纭呮鐎规娊鎯冮崟顒傛Х闁绘粣鎷�
			int widthRatio = Math.round((float) width / (float) reqWidth);
			int heightRatio = Math.round((float) width / (float) reqWidth);
			inSampleSize = Math.max(widthRatio, heightRatio);
		}
		return inSampleSize;
	}

	/**
	 * 闁哄秷顫夊畵浣烘媼閿涘嫮鏆柣銊ュ焽nSampleSize闁挎稑鑻欢閬嶅礆閺夊灝绔剧紓鍌楁櫅閹宕堕崜褍顣�
	 * 
	 * @param pathName
	 * @param reqWidth
	 * @param reqHeight
	 * @return
	 */
	private Bitmap decodeSampledBitmapFromResource(String pathName,
			int reqWidth, int reqHeight)
	{
		// 缂佹鍏涚粩鏉戔枎闄囪闁哄鍔曢惃顣弉JustDecodeBounds閻犱礁澧介悿鍡樼▔缁ㄥ吵ue闁挎稑鏈鐢告嚔瀹勬澘绲块柛銉ュ⒔婢ф牗寰勮閻拷
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(pathName, options);
		// 閻犲鍟伴弫銈嗙▔婵犲洦妗ㄩ悗瑙勭煯缁犵喖鎯冮崟顒佺厵婵炲娲濋鍝ョ不濮婃SampleSize闁稿鎷�
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);
		// 濞达綀娉曢弫銈夋嚔瀹勬澘绲块柛鎺撳濞堟吔nSampleSize闁稿﹦鍘ч崯锟芥繛鍠°伆鎺楀几閹邦剚绂堥柣妤嬫嫹
		options.inJustDecodeBounds = false;
		Bitmap bitmap = BitmapFactory.decodeFile(pathName, options);

		return bitmap;
	}

	private class ImgBeanHolder
	{
		Bitmap bitmap;
		ImageView imageView;
		String path;
	}

	private class ImageSize
	{
		int width;
		int height;
	}

	/**
	 * 闁告瑥绉撮惃鐘绘嚔瀹勬壆绻両mageView閻犱礁澧介悿鍡涙儍閸曨剚浠樺鍫嗗喚鍟嶉幖杈剧畱閹风増顨囧Ο鍝勵唺
	 * 
	 * @param object
	 * @param fieldName
	 * @return
	 */
	private static int getImageViewFieldValue(Object object, String fieldName)
	{
		int value = 0;
		try
		{
			Field field = ImageView.class.getDeclaredField(fieldName);
			field.setAccessible(true);
			int fieldValue = (Integer) field.get(object);
			if (fieldValue > 0 && fieldValue < Integer.MAX_VALUE)
			{
				value = fieldValue;

				Log.e("TAG", value + "");
			}
		} catch (Exception e)
		{
		}
		return value;
	}

}
